package com.mach.platform.sprider.dev.virdev;

import com.mach.platform.sprider.dev.UU;
import com.mach.platform.sprider.getter.CmdMainWork;
import com.mach.platform.sprider.getter.DevFactory;
import com.mach.platform.sprider.getter.GeneralDev;
import com.mach.platform.sprider.getter.GeneralModbusDev;
import com.mach.platform.sprider.getter.DataLogService;
import com.mach.platform.util.SqlHelper;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Map;

@Slf4j
public class PressKeeperAutoCtrl extends GeneralModbusDev implements VirDev {

    public static final int MAX_FREP = 490;
    public static final int MIX_FREP = 0;
    private Map<Object,Object> devPropsMap;


    private SqlHelper sqlHelper;
    private  DataLogService dataLogService;
    private  Map<String, Object> devInfoMap;
    private boolean isOpen = false;
    private TransducerCtrDev[] tas;
    private long lastCmdTime = 0;
//    private  Integer devId;


    public PressKeeperAutoCtrl(Map<String, Object> devInfoMap, SqlHelper sqlHelper, DataLogService dataLogService) throws SQLException {
        super(devInfoMap, sqlHelper, dataLogService);

        this.devInfoMap = devInfoMap;

        this.sqlHelper = sqlHelper;

        this.dataLogService = dataLogService;

        this.devPropsMap = sqlHelper.getMapFrTable("name", "value",
                "select name, value value " +
                        " from iot_dev_prop prop " +
                        " where prop.dev_id=" + this.devId);




    }

    private void initCtrInfo(){

        this.tas = new TransducerCtrDev[4];

        this.tas[0] = (TransducerCtrDev)DevFactory.getById(141); //1#变频器
        this.tas[1] = (TransducerCtrDev)DevFactory.getById(150); //2#变频器
        this.tas[2] = (TransducerCtrDev)DevFactory.getById(151); //3#变频器
        this.tas[3] = (TransducerCtrDev)DevFactory.getById(152); //4#变频器
    }

    @Override
    protected void pick() {
        try {
            this.devPropsMap = sqlHelper.getMapFrTable("name", "value",
                    "select name, value value " +
                            " from iot_dev_prop prop " +
                            " where prop.dev_id=" + this.devId);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        Integer auto = Integer.parseInt((String)this.devPropsMap.get("auto"));
        if(auto == 1){
            this.isOpen = true;
        }else{
            this.isOpen = false;
        }
        if(!this.isOpen ){
            UU.sleep(1000*5);
            return;
        }else{

        }

        long cur = System.currentTimeMillis();
        if( (cur - this.lastCmdTime) <  1000*5){
            UU.sleep(1000*1);
            return;
        }
        initCtrInfo();

        Double upValue = Double.parseDouble((String)this.devPropsMap.get("setUp"));
        Double downValue = Double.parseDouble((String)this.devPropsMap.get("setDown"));

        GeneralDev pressDev = DevFactory.getById(78); //压力传感器

        try {
            Double press = (Float) pressDev.getValueByCollName("压力") * 1.0;

            if(press < downValue){ //超下限

                TransducerCtrDev ta = this.findMostUpTransducer();
                if(ta != null){
                    int curFrep = ta.getFrep();
                    int willFrep = curFrep + 50;
                    if(willFrep > MAX_FREP){
                        willFrep = MAX_FREP;
                    }
                    if(willFrep < 300){
                        willFrep = 300;
                    }
                    CmdMainWork.commitCmd(ta.getDevId(),"setFrep","" + willFrep);
                    this.lastCmdTime = System.currentTimeMillis();
                }
            }
            if(press > upValue){ //超上限
                TransducerCtrDev ta = this.findMostDownTransducer();
                if(ta != null){
                    int curFrep = ta.getFrep();
                    int willFrep = curFrep - 50;
                    if(willFrep <= MIX_FREP){
                        willFrep = MIX_FREP;
                    }
                    if(willFrep < 300){
                        willFrep = 0;
                    }
                    CmdMainWork.commitCmd(ta.getDevId(),"setFrep","" + willFrep);
                    this.lastCmdTime = System.currentTimeMillis();
                }

            }

        } catch (IOException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }


    }

    private TransducerCtrDev findMostUpTransducer() {
        TransducerCtrDev tr = null;
        Integer maxFrep = null;
        TransducerCtrDev tmpDev = null;
        for( TransducerCtrDev dev : this.tas ){
            //给定频率
            try {
                Short outFrep = (Short)dev.getValueByCollName("输出频率");
                if(outFrep == null){
                    continue;
                }else{
                     tmpDev = dev;
                }
                if(maxFrep == null){
                    maxFrep = dev.getFrep();
                }
                Integer frep = dev.getFrep();
                if(frep >= maxFrep && frep < 490){
                    maxFrep = frep;
                    tr = dev;
                }


            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if(tr == null)tr = tmpDev;
        return tr;
    }
    private TransducerCtrDev findMostDownTransducer() {
        TransducerCtrDev tr = null;
        Integer mixFrep = MAX_FREP;
        TransducerCtrDev tmpDev = null;
        for( TransducerCtrDev dev : this.tas ){
            //给定频率
            try {
                Short outFrep = (Short)dev.getValueByCollName("输出频率");
                if(outFrep == null){
                    continue;
                }else{
                    tmpDev = dev;
                }
                if(mixFrep == null){
                    mixFrep = dev.getFrep();
                }
                Integer frep = dev.getFrep();
                if(frep <= mixFrep && frep > 0){
                    mixFrep = frep;
                    tr = dev;
                }


            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if(tr == null)tr = tmpDev;
        return tr;
    }

    @Override
    public void cmd(Integer cmdLogId,String cmd, String param) {

        try {
            Integer devTypeId = (Integer)this.devInfoMap.get("devTypeId");

//            Map<Object, Object> addrMap = sqlHelper.getMapFrTable("name", "valueAddr",
//                    "select name, value_addr valueAddr " +
//                            " from iot_coll_items colls " +
//                            " where colls.dev_type_id=" + devTypeId);

//            if(ctrModelValue != null && ctrModelValue.equals(1.0)){//远程
            if("open".equals(cmd) ){
                this.isOpen = true;
                sqlHelper.update("replace into iot_dev_prop(name,value,dev_id)" +
                        "value('auto','1',"+devId+")");
            }
            if("close".equals(cmd) ){
                this.isOpen = false;
                sqlHelper.update("replace into iot_dev_prop(name,value,dev_id)" +
                        "value('auto','0',"+devId+")");
            }
            if("setUp".equals(cmd) && param != null ){
                sqlHelper.update("replace into iot_dev_prop(name,value,dev_id)" +
                        "value('setUp','"+param+"',"+devId+")");
            }
            if("setDown".equals(cmd) && param != null ){
                sqlHelper.update("replace into iot_dev_prop(name,value,dev_id)" +
                        "value('setDown','"+param+"',"+devId+")");
            }

            sqlHelper.update(
                    "update iot_dev_cmd_log set resp_code=1,resp_ctx='"+EXE_SUCS_CTX+"' where id=" + cmdLogId);

        } catch (Exception e) {
            e.printStackTrace();
            sqlHelper.updateAsync(
                    "update iot_dev_cmd_log set resp_code=0,resp_ctx='"+e.getLocalizedMessage()+"' where id=" + cmdLogId);
        }finally {
            sqlHelper.updateAsync(
                    "update iot_dev_cmd_log set resp_time=now() where id=" + cmdLogId);
        }




        return;
    }

    @Override
    public Integer getDevId() {
        return this.devId;
    }


}
